/**
 * API Client Service
 * Requirements: 3.1, 4.1
 * 
 * Handles communication with the backend API
 */

import { 
  AnalyzeEmotionRequest, 
  AnalyzeEmotionResponse,
  GenerateImageRequest,
  GenerateImageResponse,
  ErrorType,
  AppError
} from '../types';

// API base URL - defaults to localhost:3001 for development
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3001';

/**
 * Create an AppError from a fetch error
 */
function createAppError(error: unknown, defaultMessage: string): AppError {
  if (error instanceof TypeError && error.message.includes('fetch')) {
    return {
      type: ErrorType.NETWORK_ERROR,
      message: '网络连接失败，请检查网络设置',
      retryable: true,
      details: error,
    };
  }
  
  return {
    type: ErrorType.UNKNOWN_ERROR,
    message: defaultMessage,
    retryable: true,
    details: error,
  };
}

/**
 * Analyze emotion from user text
 * Requirements: 3.1
 */
export async function analyzeEmotion(text: string): Promise<AnalyzeEmotionResponse> {
  try {
    const request: AnalyzeEmotionRequest = { text };
    
    const response = await fetch(`${API_BASE_URL}/api/emotion/analyze`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      
      // Handle rate limit errors
      if (response.status === 429) {
        throw {
          type: ErrorType.RATE_LIMIT_ERROR,
          message: '请求过于频繁，请稍后再试',
          retryable: true,
          details: errorData,
        } as AppError;
      }
      
      throw {
        type: ErrorType.API_ERROR,
        message: errorData.error || '情绪分析失败',
        retryable: response.status >= 500,
        details: errorData,
      } as AppError;
    }
    
    const data: AnalyzeEmotionResponse = await response.json();
    return data;
  } catch (error) {
    if ((error as AppError).type) {
      throw error;
    }
    throw createAppError(error, '情绪分析失败，请重试');
  }
}

/**
 * Generate image from prompt
 * Requirements: 4.1
 */
export async function generateImage(prompt: string): Promise<GenerateImageResponse> {
  try {
    const request: GenerateImageRequest = { prompt };
    
    const response = await fetch(`${API_BASE_URL}/api/image/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      
      // Handle rate limit errors
      if (response.status === 429) {
        throw {
          type: ErrorType.RATE_LIMIT_ERROR,
          message: '请求过于频繁，请稍后再试',
          retryable: true,
          details: errorData,
        } as AppError;
      }
      
      throw {
        type: ErrorType.API_ERROR,
        message: errorData.error || '图片生成失败',
        retryable: response.status >= 500,
        details: errorData,
      } as AppError;
    }
    
    const data: GenerateImageResponse = await response.json();
    return data;
  } catch (error) {
    if ((error as AppError).type) {
      throw error;
    }
    throw createAppError(error, '图片生成失败，请重试');
  }
}
